<template xmlns:div="http://www.w3.org/1999/html">
  <n-modal v-model:show="isVisible" title="采购单" preset="dialog" @close="onClose" @update:show="onClose"
           style="height: 420px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="采购产品：" path="productId">
          <n-select
              v-model:value="form.productId"
              :options="products"
              style="width: 200px"
              disabled></n-select>
        </n-form-item>
        <n-form-item label="采购数量：" path="quantity" style="margin-left: 20px">
          <n-input v-model:value="form.quantity" placeholder="请输入采购数量" style="width: 200px" disabled/>
        </n-form-item>
        <n-form-item label="花费金额：" path="price" style="margin-left: 20px">
          <n-input v-model:value="form.price" placeholder="请输入花费金额" style="width: 200px" disabled/>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="入库仓库：" path="storeId">
          <n-select
              v-model:value="form.storeId"
              :options="stores"
              style="width: 420px"
              disabled></n-select>
        </n-form-item>
        <n-form-item label="供货商：" path="supplierId" style="margin-left: 20px">
          <n-select
              v-model:value="form.supplierId"
              :options="suppliers"
              style="width: 200px"
              disabled>
          </n-select>
        </n-form-item>
      </div>
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="联系人：" path="adminId">
          <n-select
              v-model:value="form.adminId"
              :options="contactPersons"
              style="width: 350px"
              disabled></n-select>
        </n-form-item>
        <n-form-item label="联系电话：" path="contactPhone" style="margin-left: 20px">
          <n-input v-model:value="form.contactPhone" placeholder="请输入联系电话" style="width: 350px" disabled/>
        </n-form-item>
        <n-form-item label="状态：" path="status" style="margin-left: 20px">
          <n-select
              v-model:value="form.status"
              :options="status"
              style="width: 350px"
          ></n-select>
        </n-form-item>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-row">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import {ref, watch} from 'vue';
import {useRouter} from 'vue-router';
import {useUserStore} from "@/store/index.js";
import api from '@/api/admin'
import {List} from "echarts";

const router = useRouter()
const userStore = useUserStore()
const id = userStore.getId();
const loading = ref(true)

const emit = defineEmits(['updatePage'])
const props = defineProps({
  show1: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
  option: {
    type: List,
    require: true
  },
  products: {
    type: Array,
    required: true
  },
  stores: {
    type: Array,
    required: true
  },
  suppliers: {
    type: Array,
    required: true
  },
  contactPersons: {
    type: Array,
    required: true
  },
  attribute: {
    type: Object,
    required: true,
  }
});
const status = ref([
  {
    label: '待采购',
    value: '待采购',
  },
  {
    label: '采购中',
    value: '采购中',
  },
  {
    label: '已完成',
    value: '已完成',
  },
  {
    label: '已取消',
    value: '已取消',
  }
])
const isVisible = ref(props.show1);
watch(() => props.show1, (newVal) => {
  isVisible.value = newVal;
  if (newVal) {
    // 当对话框显示时，将传递过来的属性值填充到表单中
    form.value = {...props.attribute};
		console.log(form.value)
  }
});
const form = ref({
  productId: null,
  storeId: null,
  quantity: '',
  price: '',
  supplierId: null,
  contactPhone: '',
  adminId: null,
  status: ''
});
// 获取当前时间并格式化的函数
function getCurrentFormattedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const handleSubmit = async () => {
  try {
    const res = await api.updatePurchaseOrder(
        {
          ...form.value,
        }
    )
    if (res.code === 200) {
      emit("updatePage")
      $message.success("修改采购单状态成功！")
    } else {
      $message.error(res.message)
    }
    if (form.value.status === '已完成') {
      const res1 = await api.addFinanceReceipt(
          {
            ...form.value,
            orderType: "purchase_order",
            type: "out",
            id:"",
            createTime: props.attribute.createTime,
            orderId:props.attribute.id,
            endTime: getCurrentFormattedTime(),
          }
      )
      if (res1.code === 200) {
        emit("updatePage")
      } else {
        $message.error(res1.message)
      }
      const res2 = await api.addInboundDocument(
          {
            ...form.value,
            adminId: id,
            id:"",
            type:"inbound",
            storeId:form.value.storeId,
            productId:form.value.productId,
            objectId: form.value.adminId,
            price:form.value.price,
            quantity:form.value.quantity
          }
      )
      if (res2.code === 200) {
        emit("updatePage")
      }
      else {
        $message.error(res2.message)
      }
    }
  } catch (err) {
    $message.error("修改采购单状态失败！")
  } finally {
    clear()
    props.onClose();
  }
};
const clear = () => {
  form.value.adminId = null
  form.value.productId = null
  form.value.storeId = null
  form.value.supplierId = null
  form.value.price = ""
  form.value.quantity = ""
  form.value.contactPhone = ""
}

</script>
<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative;
}

.form-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-row > n-form-item {
  flex: 1;
}

.submit-row {
  justify-content: center;
  display: flex;
  width: 100%;
}
</style>
